<?php


namespace apps\marriage\app\mp\controller;


use apps\marriage\core\logic\WeixinMpLogic;
use apps\marriage\core\model\MemberProfile;
use apps\marriage\core\service\MemberImagesService;
use apps\marriage\core\service\MemberLikesService;
use apps\marriage\core\service\MemberProfileService;
use apps\marriage\core\service\MemberRechargeRecordService;
use apps\marriage\core\service\MemberVisitService;
use apps\marriage\core\service\SiteConfigService;
use apps\marriage\core\service\UserCheckInService;
use apps\marriage\core\service\UserPlatformService;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\facade\Log;
use think\Request;

class MemberController extends BaseMarriageMpController
{
    /**
     * @var MemberProfileService
     */
    private $memberProfileService;

    /**
     * @var MemberVisitService
     */
    private $memberVisitService;

    /**
     * @var MemberLikesService
     */
    private $memberLikesService;

    /**
     * @var MemberRechargeRecordService
     */
    private $memberRechargeRecordService;

    /**
     * @var MemberImagesService
     */
    private $memberImagesService;

    /**
     * @var UserService
     */
    private $userService;

    /**
     * @var UserPlatformService
     */
    private $userPlatformService;

    /**
     * @var UserCheckInService
     */
    private $userCheckInService;

    /**
     * @var WeixinMpLogic
     */
    private $weixinMpLogic;

    /**
     * @var SiteConfigService
     */
    private $siteConfigService;

    protected function init()
    {
        parent::init();
        $this->memberProfileService = service('MemberProfile', SERVICE_NAMESPACE);
        $this->memberVisitService = service('MemberVisit', SERVICE_NAMESPACE);
        $this->memberLikesService = service('MemberLikes', SERVICE_NAMESPACE);
        $this->memberRechargeRecordService = service('MemberRechargeRecord', SERVICE_NAMESPACE);
        $this->userService = service('User', SERVICE_NAMESPACE);
        $this->userPlatformService = service('UserPlatform', SERVICE_NAMESPACE);
        $this->userCheckInService = service('UserCheckIn', SERVICE_NAMESPACE);
        $this->memberImagesService = service('MemberImages', SERVICE_NAMESPACE);
        $this->weixinMpLogic = logic('WeixinMp', LOGIC_NAMESPACE);
        $this->siteConfigService = service('SiteConfig', SERVICE_NAMESPACE);
    }

    public function lists(Request $request)
    {
        $page = $request->param('page', 1, 'intval');
        $pageSize = $request->param('page_size', 10, 'intval');
        $keywords = $request->param('keywords', '');
        $order = $request->param('order', 10, 'intval');
        $gender = $request->param('gender', 0, 'intval');
        $minAge = $request->param('min_age', 0, 'intval');
        $maxAge = $request->param('max_age', 0, 'intval');
        $liveProvince = $request->param('live_province', 0, 'intval');
        $liveCity = $request->param('live_city', 0, 'intval');
        $heightFrom = $request->param('height_from', 0, 'intval');
        $heightTo = $request->param('height_to', 0, 'intval');
        $weightFrom = $request->param('weight_from', 0, 'intval');
        $weightTo = $request->param('weight_to', 0, 'intval');
        $marriageStatus = $request->param('marriage_status', 0, 'intval');
        $education = $request->param('education', 0, 'intval');
        $job = $request->param('job', -1, 'intval');
        $annualIncome = $request->param('annual_income', 0, 'intval');
        $zodiac = $request->param('zodiac', -1, 'intval');   // 生肖
        $kids = $request->param('kids', 0, 'intval');
        $constellation = $request->param('constellation', '', 'intval');   //  星座
        $houseStatus = $request->param('house_status', 0, 'intval');
        $houseLocation = $request->param('house_location', 0, 'intval');
        $carStatus = $request->param('car_status', 0, 'intval');
        $birthProvince = $request->param('birth_province', 0, 'intval');
        $birthCity = $request->param('birth_city', 0, 'intval');

        $params = [
            'keywords' => $keywords,
            'marriage_seeking_status' => 1
        ];
        if($gender > 0) {
            $params['gender'] = $gender;
        }
        if($maxAge > 0) {
            $params['birthday_from'] = strtotime(date('Y') . '-01-01 00:00:00') - $maxAge * 3600*24*365;
        }
        if($minAge > 0) {
            $params['birthday_to'] = strtotime(date('Y') . '-12-30 23:59:59') - $minAge * 3600*24*365;
        }
        if($liveProvince > 0) {
            $params['live_province'] = $liveProvince;
        }
        if($liveCity > 0) {
            $params['live_city'] = $liveCity;
        }
        if($heightFrom > 0 && $heightTo > 0) {
            $params['height_from'] = $heightFrom;
            $params['height_to'] = $heightTo;
        }
        if($weightFrom > 0 && $weightTo > 0) {
            $params['weight_from'] = $weightFrom;
            $params['weight_to'] = $weightTo;
        }
        if($marriageStatus > 0) {
            $params['marriage_status'] = $marriageStatus;
        }
        if($education > 0) {
            $params['education'] = $education;
        }
        if($job > -1) {
            $params['job'] = $job;
        }
        if($annualIncome > 0) {
            $params['annual_income'] = $annualIncome;
        }
        if($zodiac > -1) {   // 生肖
            $params['zodiac'] = $zodiac;
        }
        if($constellation) {   // 星座
            $constellations = constellations();
            $k = 0;
            foreach ($constellations as $index => $val) {
                if($constellation == $index) {
                    $params['constellation'] = $k;
                    break;
                }
                $k++;
            }
        }
        if($kids > 0) {
            $params['kids'] = $kids;
        }
        if($houseStatus > 0) {
            $params['house_status'] = $houseStatus;
        }
        if($houseLocation > 0) {
            $params['house_location'] = $houseLocation;
        }
        if($carStatus > 0) {
            $params['car_status'] = $carStatus;
        }
        if($birthProvince > 0) {
            $params['birth_province'] = $birthProvince;
        }
        if($birthCity > 0) {
            $params['birth_city'] = $birthCity;
        }

        $res = $this->memberProfileService->search($params, $page, $pageSize);
        if($res['data']) {
            $dataList = [];
            foreach ($res['data'] as $rs) {
                $user = $this->userService->getByPk($rs['user_id']);
                $user = arrayOnly($user, ['id', 'nick', 'avatar_url']);
                $dataList[] = [
                    'member' => $this->memberProfileService->format($rs),
                    'user' => $user
                ];
            }
            $res['data'] = $dataList;
        }
        return $this->success($res);
    }

    public function recommend(Request $request)
    {
        $pageSize = $request->param('page_size', 10, 'intval');
        $recommendType = $request->param('recommend_type', 0, 'intval');
        $params = [
            'recommend_type' => $recommendType
        ];
        $res = $this->memberProfileService->pageListByParams($params, $pageSize);
        if(!empty($res['data'])) {
            $dataList = [];
            foreach ($res['data'] as $rs) {
                $user = $this->userService->getByPk($rs['user_id']);
                $user = arrayOnly($user, ['id', 'nick', 'avatar_url']);
                $dataList[] = [
                    'member' => $this->memberProfileService->format($rs),
                    'user' => $user
                ];
            }
            $res['data'] = $dataList;
        }
        return $this->success($res);
    }

    public function profile(Request $request)
    {
        $from = $request->param('from', '');
        $id = $request->param('id', 0, 'intval');
        $member = $this->memberProfileService->getByPk($id);
        if(empty($member) || $member['marriage_seeking_status'] == 0) {
            throw new Exception('该会员不存在');
        }
        $member = $this->memberProfileService->format($member);
        $user = $this->userService->getByPk($member['user_id']);
        if (stripos($user['mobile'], "000") === 0) {
            $member['phone_auth_status'] = 0;
        } else {
            $member['phone_auth_status'] = 1;
        }

        $user = arrayOnly($user, ['id', 'nick', 'avatar_url']);

        if($from == 'member_profile' && $this->user && $this->user['id'] != $member['user_id']) {
            $this->memberVisitService->save($this->user['id'], $id);
        }

        if($this->user) {
            if($this->memberLikesService->info([
                'user_id' => $this->user['id'],
                'member_profile_id' => $id
            ])) {
                $member['liked'] = true;
            } else {
                $member['liked'] = false;
            }
        } else {
            $member['liked'] = false;
        }

        $member = arrayExcept($member, ['wxid']);

        $images = $this->memberImagesService->getAllByUserId($member['user_id']);

        return $this->success([
            'member' => $member,
            'user' => $user,
            'images' => $images
        ]);
    }

    public function profile_by_user_id(Request $request)
    {
        $userId = $request->param('user_id', 0, 'intval');
        $member = $this->memberProfileService->getByUserId($userId);
        if(empty($member)) {
            throw new Exception('该会员不存在');
        }
        $member = $this->memberProfileService->format($member);
        $member = arrayExcept($member, ['wxid']);
        $user = $this->userService->getByPk($member['user_id']);
//        if (stripos($user['mobile'], "000") === 0) {
//            $member['phone_auth_status'] = 0;
//        } else {
//            $member['phone_auth_status'] = 1;
//        }
        $member['phone_auth_status'] = 1;
        $user = arrayOnly($user, ['id', 'nick', 'avatar_url']);

        return $this->success([
            'member' => $member,
            'user' => $user
        ]);
    }

    public function check_in()
    {
        $rewardGoldCoin = $this->userCheckInService->create([
           'user_id' => $this->user['id']
        ]);
        $user = $this->userService->getByPk($this->user['id']);
        $userDto = arrayExcept($user, ['password', 'password_salt', 'mobile']);
        return $this->success([
            'reward_gold_coin' => $rewardGoldCoin,
            'gold_coin' => $userDto['gold_coin']
        ]);
    }

    public function my_check_in()
    {
        $beginTime = strtotime(date('Ymd') . ' 00:00:00');
        $endTime = strtotime(date('Ymd') . ' 23:59:59');
        $record = $this->userCheckInService->getByLimitTime($this->user['id'], $beginTime, $endTime);
        return $this->success([
            'checked' => $record ? true : false
        ]);
    }

    public function vip_levels()
    {
        $site = config('site');
        return $this->success([
            'vip_levels' => $site['vip_levels']
        ]);
    }

    public function constants()
    {
        return $this->success([
            'genders' => MemberProfile::genders(),
            'incomes' => MemberProfile::incomes(),
            'jobs' => MemberProfile::jobs(),
            'nations' => MemberProfile::nations(),
            'blood_types' => MemberProfile::bloodTypes(),
            'kids' => MemberProfile::kids(),
            'faiths' => MemberProfile::faiths(),
            'drinks' => MemberProfile::drinks(),
            'smokes' => MemberProfile::smokes(),
            'job_types' => MemberProfile::jobTypes(),
            'education_types' => MemberProfile::educationTypes(),
            'marriage_status' => MemberProfile::marriageStatus(),
            'house_status' => MemberProfile::houseStatus(),
            'car_status' => MemberProfile::carStatus(),
            'distance_relationship_types' => MemberProfile::distanceRelationshipTypes(),
            'child_types' => MemberProfile::childTypes(),
            'live_parents_types' => MemberProfile::liveParentsTypes(),
            'zodiacs' => zodiacs(),
            'constellations' => constellations()
        ]);
    }

    public function like(Request $request)
    {
        $memberId = $request->param('member_id', 0, 'intval');
        $this->memberLikesService->save($this->user['id'], $memberId);

        $member = $this->memberProfileService->getByPk($memberId);
        $member = $this->memberProfileService->format($member);

        if($this->memberLikesService->info([
            'user_id' => $this->user['id'],
            'member_profile_id' => $memberId
        ])) {
            $member['liked'] = true;
        } else {
            $member['liked'] = false;
        }

        return $this->success(['member' => $member]);
    }

    public function view_wxid(Request $request)
    {
        $memberId = $request->param('member_id', 0, 'intval');
        $result = $this->memberProfileService->onViewWxid($this->user['id'], $memberId);
        return $this->response($result['code'], '', [
            'wxid' => $result['wxid']
        ]);
    }

    public function unlock_phone(Request $request)
    {
        $memberId = $request->param('member_id', 0, 'intval');
        $result = $this->memberProfileService->onUnlockPhoneNumber($this->user['id'], $memberId);
        return $this->response($result['code'], '', [
            'phone_number' => $result['phone']
        ]);
    }

    public function share_poster(Request $request)
    {
        $memberId = $request->param('member_id');
        $fromuid = $request->param('fromuid');
        $url = $this->memberProfileService->getSharePoster($memberId, $fromuid);
        return $this->success([
            'url' => $url
        ]);
    }

    public function my_share_poster()
    {
        $url = $this->memberProfileService->getMySharePoster($this->user['id']);
        return $this->success([
            'url' => $url
        ]);
    }

    public function my_qrcode_img()
    {
        $url = $this->memberProfileService->myQrCodeImg($this->user['id']);
        return $this->success([
            'url' => $url
        ]);
    }
}